<template>
	<view class="page video-manage-page">
		<view class="footer" flex>
			<view>
				<u-button type="primary" size="mini" :hair-line="false" @click="confirm" style="margin-right: 8px;">确定
				</u-button>
				<u-button :hair-line="false" size="mini" @click="cancel">取消</u-button>
			</view>
		</view>
		<view class="container">
			<view class="upload-box" flex="corss:center main:center">
				<view class="upload-item" v-for="(video, index) in formData.videoList" :key="index">
					<view class="block">
						<image :src="video.thumbnailUrl" mode=""></image>
					</view>
					<view class="action" :style="{ opacity: index == actionIndex ? 1 : 0 }">
						<view class="action-wrap" @click.stop="showAction(index)">
							<text class="iconfont icon-preview" style="font-size: 46upx;"
								@click.stop="previewVideo(video.url)">&#xec13;</text>
							<text class="iconfont icon-delete" style="font-size: 46upx;"
								@click.stop="onDeleteVideo(video, index)">&#xe74b;</text>
						</view>
					</view>
				</view>
				<uni-file-picker :limit="3" :sourceType="sourceType" v-model="imageValue" fileMediatype="video"
					mode="grid" :list-styles="listStyles" @select="select">
					<view class="add block">
						<u-icon name="plus" color="#8c939d" size="56"></u-icon>
					</view>
				</uni-file-picker>
			</view>
			<view class="form-box">
				<scroll-view scroll-y="true" class="scroll-Y" style="height:100%">
					<view class="form-list" flex>
						<view class="form-item" v-for="(video, index) in formData.videoList">
							<u-form :model="video.form" ref="uForm" class="apply-form-field" label-width="150">
								<u-form-item label="拍摄地点" prop="address">
									<u-input v-model="video.form.address" />
								</u-form-item>
								<u-form-item label="视频分类" prop="category" right-icon="arrow-right">
									<u-input v-model="video.form.category" placeholder="请选择" disabled
										@click="onShowTypePopup('category', index)" />
								</u-form-item>
								<u-form-item label="拍摄时间" prop="creatTime" right-icon="arrow-right">
									<view style="text-align: right;width: 100%;" @click.stop="onShowTime(index)">
										{{ formatTime(video.form.creatTime) }}
									</view>
								</u-form-item>
								<u-form-item label="拍摄方向" prop="direction" right-icon="arrow-right">
									<u-input v-model="video.form.direction" placeholder="请选择" disabled
										@click="onShowTypePopup('direction', index)" />
								</u-form-item>
								<u-form-item label="拍摄人" prop="person">
									<u-input v-model="video.form.person" />
								</u-form-item>
								<u-form-item label="证据来源" prop="resource" right-icon="arrow-right">
									<u-input v-model="video.form.resource" placeholder="请选择" disabled
										@click="onShowTypePopup('resource', index)" />
								</u-form-item>
								<u-form-item label="拍摄设备" prop="device">
									<u-input v-model="video.form.device" placeholder="请输入" class="form-field-select" />
								</u-form-item>
								<u-form-item label="标签" prop="tag" right-icon="arrow-right">
									<u-input v-model="video.form.tag" placeholder="请选择" disabled
										@click="onShowTypePopup('tag', index)" />
								</u-form-item>
							</u-form>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>

		<view class="video-wrap" v-if="videoShow">
			<video id="myVideo" :src="videoUrl" controls @fullscreenchange="fullscreenchange"
				@loadedmetadata="loadedmetadata"></video>
		</view>
		<u-picker mode="time" :defaultTime="timeObj.defaultStartTime" v-model="timeObj.show" :params="timeObj.params"
			@confirm="confirmTimePicker"></u-picker>
		<u-select v-model="popupSelect.show" mode="single-column" :list="popupSelect.list" value-name="dictValue"
			label-name="dictLabel" @confirm="confirmSelect"></u-select>
	</view>
</template>
<script>
	import {
		dicDataMap
	} from '@/const';
	import {
		videoThumbnail
	} from '@/static/common/js/videoThumbnail';
	export default {
		data() {
			return {
				videoList: [],
				imageValue: [],
				listStyles: {
					borderStyle: {
						color: 'red', // 边框颜色
						width: '1px', // 边框宽度		3wa
						style: 'solid', // 边框样式
						radius: '5px' // 边框圆角，不支持百分比
					},
					border: true, // 是否显示边框
					dividline: true // 是否显示分隔线
				},
				params: {},
				currentRow: {},
				formData: {},
				form: {
					address: '',
					category: '',
					creatTime: new Date().getTime(),
					direction: '',
					person: '',
					resource: '',
					device: '华为平板',
					tag: ''
				},
				directionDict: dicDataMap,
				categoryDict: [],
				resourceDict: [],
				tagDict: [],
				popupSelect: {
					type: '',
					show: false,
					list: [],
					index: null
				},
				timeObj: {
					show: false,
					defaultTime: new Date(),
					index: null,
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true,
						timestamp: true
					}
				},
				actionIndex: null,
				videoUrl: '',
				videoShow: false,
				videoContext: '',
				sourceType: ['album']
			};
		},
		async onLoad(params) {
			this.params = params;
			const {
				archivesId,
				dictId,
				noticeId,
				currentIndex
			} = params;
			const data = await this.getDetailByNoticeId(dictId, noticeId);
			this.currentRow = data || {
				archivesId,
				dictId
			};
			if (currentIndex || currentIndex == 0) {
				this.formData = data.jsonStr && JSON.parse(data.jsonStr)[currentIndex];
			} else {
				this.initForm();
				console.log(this.formData);
			}
			console.log(this.formData);
			let pArr = [this.getDictData('video_category'), this.getDictData('resource_type'), this.getDictData(
				'tag_type')];
			Promise.all(pArr).then(res => {
				this.categoryDict = res[0].data;
				this.resourceDict = res[1].data;
				this.tagDict = res[2].data;
			});
		},
		computed: {
			formatTime() {
				return time => {
					return this.$u.timeFormat(time, 'yyyy年mm月dd日');
				};
			},
			formatAddress() {
				return address => {
					if (!address || !address.length) return '--';
					return address.split(',')[2];
				};
			}
		},
		onShow() {},
		methods: {
			showAction(index) {
				console.log(index);
				if (index == this.actionIndex) {
					this.actionIndex = null;
					return;
				}
				this.actionIndex = index;
			},
			async getDetailByNoticeId(dictId, noticeId) {
				return await this.$u.api.record.info(dictId, noticeId).then(res => {
					console.log(res);
					if (res.code == 200) {
						return res.data;
					}
				});
			},
			async uploadImg(path) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.vuex_config.baseUrl + '/common/upload', //仅为示例，非真实的接口地址
						filePath: 'file://' + path, // 获取到的路径 要加 file://
						header: {
							Authorization: this.vuex_token
						},
						name: 'file',
						success(uploadFileRes) {
							let fileResData = JSON.parse(uploadFileRes.data);
							if (uploadFileRes.statusCode == 200 && fileResData.code == 200) {
								resolve(fileResData.data);
							}
						},
						fail: e => {
							console.log('error', e);
						}
					});
				});
			},
			// 获取上传状态
			select(e) {
				let that = this;
				console.log('选择文件：', e);
				this.form.address = this.formatAddress(this.vuex_archives.fireAddress);
				this.form.person = this.formData.userName;

				uni.getVideoInfo({
					src: e.tempFilePaths[0],
					success: (videoInfo) => {
						console.log(videoInfo);
						console.log(e.tempFilePaths);
						this.form.duration = videoInfo.duration
						let formDeep = this.$u.deepClone(this.form);
						let filePath = e.tempFilePaths[0].slice(6); // 只针对相册选择模式
						console.log(filePath);
						videoThumbnail(filePath, 'hd_video_' + new Date().getTime()).then(async file => {
							// console.log(file);
							let data = await this.uploadImg(file.fullPath);
							that.formData.videoList.push({
								tempFiles: e.tempFiles,
								url: e.tempFilePaths[0],
								form: formDeep,
								thumbnailUrl: data.url
							});
						});
					}
				})
			},
			confirm() {
				const {
					currentIndex,
					dictId,
					archivesId
				} = this.params;
				console.log(this.currentRow);
				let {
					jsonStr
				} = this.currentRow;
				jsonStr = jsonStr && jsonStr != '' ? JSON.parse(jsonStr) : [];
				this.formData.createTime = new Date().getTime();
				if (currentIndex) {
					this.currentRow.handleType = 2;
					jsonStr.splice(currentIndex, 1, this.formData);
				} else {
					this.currentRow.handleType = 1;
					jsonStr.push(this.formData);
				}
				this.currentRow.jsonStr = JSON.stringify(jsonStr);
				console.log(dictId);
				console.log(this.currentRow);
				console.log(this.currentRow.jsonStr);
				this.$u.api.record.edit(dictId, this.currentRow).then(res => {
					console.log(res);
					if (res.code == 200) {
						let self = this;
						uni.showToast({
							title: res.msg,
							duration: 1300,
							icon: 'success',
							success() {
								setTimeout(() => {
									self.initForm();
									uni.navigateBack({
										delta: 1
									});
								}, 1000);
							}
						});
					}
				});
			},
			cancel() {
				this.initForm();
				uni.navigateBack({
					delta: 1
				});
			},
			initForm() {
				this.formData = {
					videoList: [],
					userName: this.vuex_user.nickName,
					createTime: '',
					title: `${this.vuex_user.nickName}-${this.$u.timeFormat(new Date(), 'yyyy年mm月dd日')}`
				};
			},
			getDictData(type) {
				return this.$u.api.dictData({
					isDic: true,
					dictType: type
				});
			},
			onShowTypePopup(type, index) {
				this.popupSelect.type = type;
				this.popupSelect.show = true;
				this.popupSelect.list = this[type + 'Dict'];
				this.popupSelect.index = index;
				console.log(type);
				// categoryDict: [],
				// resourceDict: [],
				// tagDict: [],
			},
			confirmSelect(e) {
				console.log(this.popupSelect);
				console.log(e);
				const {
					type,
					list,
					index
				} = this.popupSelect;
				this.formData.videoList[index].form[type] = e[0].label;
			},
			onShowTime(index) {
				console.log('123');
				// creatTime
				this.timeObj.show = true;
				this.timeObj.index = index;
			},
			confirmTimePicker(e) {
				console.log(e);
				const {
					index
				} = this.timeObj;
				let timeFormat = this.$u.timeFormat(e.timestamp, 'yyyy-mm-dd hh:MM:ss');
				this.formData.videoList[index].form['creatTime'] = timeFormat;
			},
			showVideo(video) {},
			previewVideo(video) {
				console.log(video);
				this.videoShow = true;
				this.videoUrl = video;
				this.videoContext = uni.createVideoContext('myVideo');
				// this.videoContext.requestFullScreen();
				this.videoContext.play();
				this.$nextTick(() => {
					this.videoContext.requestFullScreen();
				});
			},
			fullscreenchange(fullScreen) {
				console.log(fullScreen);
			},
			loadedmetadata(e) {
				console.log(e);
				// this.videoContext.play();
			},
			onDeleteVideo(row, index) {
				if (this.actionIndex == null) {
					return
				}
				console.log('remove');
				this.formData.videoList.splice(index, 1)
				this.actionIndex = null
				// formData.videoList
			}
		}
	};
</script>

<style lang="scss" scoped>
	.video-manage-page {
		height: calc(100vh);
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		position: relative;
		background-color: #fff;

		.container {
			padding: 30upx;
			padding-bottom: 132upx;
			overflow-y: auto;
		}
	}

	.upload-box {
		flex-wrap: wrap;

		.upload-item {
			position: relative;
		}

		.block,
		.action {
			// width: 296upx;
			// height: 296upx;
			width: 380upx;
			height: 380upx;
		}

		.action {
			position: absolute;
			top: 0;
			left: 0;
			color: #fff;
			background-color: rgba(0, 0, 0, 0.5);
			font-size: 40upx;

			.action-wrap {
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;

				.icon-delete {
					position: absolute;
					top: 300upx;
					right: 40upx;
				}
			}
		}

		.block {
			margin: 0 16upx 16upx 0;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #fbfdff;
			border: 1px dashed #c0ccda;
			border-radius: 6px;
			word-break: break-all;
			text-align: center;

			video {
				width: 100%;
				height: 100%;
			}
		}
	}

	::v-deep .form-box {
		// position: fixed;
		width: 100%;
		// top: 420upx;
		// height: calc(100vh - 420upx - 132upx);
		/* #ifdef H5 */
		// top: 560upx;
		/* #endif */
		background-color: #fff;

		.form-list {
			flex-wrap: wrap;

			.form-item {
				width: 32%;
				margin-right: 20upx;
				margin-bottom: 20upx;

				// border: 2upx solid #dcdfe6;
				// u-form-item u-border-bottom
				.u-form-item--right {
					border-radius: 8upx;
					border: 2upx solid #dcdfe6;
					padding-right: 20upx;
				}

				.u-form-item {
					&::after {
						display: none;
					}
				}
			}
		}
	}

	::v-deep .uni-file-picker {
		overflow: inherit;
	}

	// 隐藏原生预览列表
	::v-deep .uni-file-picker__lists {
		display: none;
	}

	.footer {
		width: 100%;
		padding-right: 12px;
		justify-content: flex-end;

		.u-btn {
			display: inline-block;
		}


		.btn {
			flex: 1;
			height: 132upx;
		}

		.btn+.btn {
			margin-left: 20upx;
		}
	}
</style>
